package org.openCage.artig;

import org.openCage.artig.stjx.Artifact;
import org.openCage.artig.stjx.ArtifactRef;
import org.openCage.lang.functions.F1;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Utils {

    public static boolean isEqual( Artifact a, Artifact b ) {
        return a.getName().equals( b.getName() );
    }

    public static boolean isEqual( Artifact arti, ArtifactRef ref ) {
        return arti.getName().equals( ref.getName() );
    }

    public static boolean isEqual( ArtifactRef a, ArtifactRef b ) {
        return a.getName().equals( b.getName() );
    }

    public static Artifact find( Collection<Artifact> artis, ArtifactRef ref ) {
        for ( Artifact arti : artis ) {
            if ( isEqual( arti,ref)) {
                return arti;
            }
        }

        return null;
    }

    public static Set<ArtifactRef> transR( List<Artifact> artis, Set<ArtifactRef> set, F1<Boolean, ArtifactRef> cond ) {

        Set<ArtifactRef> next = new HashSet<ArtifactRef>();

        for ( ArtifactRef ref : set ) {
            Artifact arti = find( artis, ref );
            for ( ArtifactRef dep : arti.getDepends() ) {
                if ( cond.call( dep )) {
                    next.add( dep );
                }
            }
        }

        int start = set.size();
        set.addAll( next );

        if ( start < set.size() ) {
            return transR( artis, set, cond );
        }

        return set;
    }

    public static Set<Artifact> transA( List<Artifact> artis, Collection<ArtifactRef> start, F1<Boolean, ArtifactRef> cond ) {
        Set<Artifact> ret = new HashSet<Artifact>();

        for ( ArtifactRef ref : transR( artis, new HashSet<ArtifactRef>( start ), cond )) {
            ret.add( find( artis, ref ));
        }

        return ret;
    }


}
